//
//  M1AppleIpa.m
//  NewMarryU
//
//  Created by apple on 2018/7/22.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1AppleIpa.h"
#import <StoreKit/StoreKit.h>
@interface M1AppleIpa()<SKPaymentTransactionObserver,SKProductsRequestDelegate>
@property (nonatomic ,strong) UIViewController *m1_vc;
@property (nonatomic ,copy)   NSString *m1_ipaId;
@property (nonatomic ,strong) ReturnBlock block;
@end
@implementation M1AppleIpa
+(M1AppleIpa *)manager{
    static M1AppleIpa *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [M1AppleIpa new];
    });
    return instance;
}
-(void)m1_appIpaWithVC:(id)vc appleId:(NSString *)ipaId block:(ReturnBlock)block{
    _m1_vc = vc;
    _m1_ipaId = ipaId;
    _block = block;
    
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].delegate.window animated:NO];
    
    if(![SKPaymentQueue canMakePayments]){
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
        [M1Alert m1_alertWithTitle:nil message:@"无法购买"];
        return;
    }
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    NSArray* transactions = [SKPaymentQueue defaultQueue].transactions;
    for (SKPaymentTransaction* transaction in transactions) {
        if (transaction.transactionState == SKPaymentTransactionStatePurchased || transaction.transactionState == SKPaymentTransactionStateFailed) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }
    }
    NSArray *product = [[NSArray alloc] initWithObjects:_m1_ipaId,nil];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:{
                [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
            }break;
            case SKPaymentTransactionStatePurchased:{
                [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
                [queue finishTransaction:transaction];
                NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
                NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
                NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
                if (self.block) {
                    self.block(receiptString);
                }
            }break;
            case SKPaymentTransactionStateFailed:{
                [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
                [M1Alert m1_alertWithTitle:nil message:@"购买失败"];
        
                [queue finishTransaction:transaction];
            }break;
            case SKPaymentTransactionStateRestored:{
                [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
                [queue finishTransaction:transaction];
            }break;
            case SKPaymentTransactionStateDeferred:{
                [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].delegate.window animated:NO];
            }break;
            default:
                break;
        }
    }
}
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *products = response.products;
    if (products.count == 0) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
        [M1Alert m1_alertWithTitle:nil message:@"没有此类商品"];
        return;
    }
    SKProduct *product = nil;
    for (SKProduct *pro in products) {
        if([pro.productIdentifier isEqualToString:_m1_ipaId]){
            product = pro;
        }
    }
    SKPayment *payment = [SKPayment paymentWithProduct:product];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
}
-(void)requestDidFinish:(SKRequest *)request{
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
}
@end
